using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SoftwareMonkeys.LiveShift.Diagnostics;

namespace SoftwareMonkeys.LiveShift.Entities
{
	public class ShiftEnvironment : IShiftEnvironment
	{
		private DateTime lastShift;
		public DateTime LastShift
		{
			get { return lastShift; }
			set { lastShift = value; }
		}
		
		private IShiftableEntity[] entities = new IShiftableEntity[]{};
		public IShiftableEntity[] Entities
		{
			get { return entities; }
			set { entities = value;
				foreach (IShiftableEntity entity in entities)
					entity.Environment = this;
			}
		}

		public IShiftResult Shift(DateTime dateTime)
		{
			IShiftResult result = new ShiftResult();
			using (LogGroup logGroup = LogGroup.Start("Shifting the environment.", NLog.LogLevel.Debug))
			{
				foreach (IShiftableEntity entity in Entities)
				{
					result.AddResult(entity.Shift(dateTime));
				}
			}
			return result;
		}

		public void AddEntity(IShiftableEntity entity)
		{
			using (LogGroup logGroup = LogGroup.Start("Adding a new shiftable entity to the environment.", NLog.LogLevel.Debug))
			{				
				entity.Environment = this;
				
				List<IShiftableEntity> entities = new List<IShiftableEntity>();
				if (Entities != null)
					entities.AddRange(Entities);
				entities.Add(entity);
				this.entities = entities.ToArray();
			}
		}
	}
}
